package com.jiajia.server.config.security;

import com.jiajia.server.pojo.Menu;
import com.jiajia.server.pojo.Role;
import com.jiajia.server.service.IMenuService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.access.ConfigAttribute;
import org.springframework.security.access.SecurityConfig;
import org.springframework.security.web.FilterInvocation;
import org.springframework.security.web.access.intercept.FilterInvocationSecurityMetadataSource;
import org.springframework.stereotype.Component;
import org.springframework.util.AntPathMatcher;

import java.util.Collection;
import java.util.List;

/**
 * 权限控制
 * 根据所需url判断所需的角色
 * @author ZSJia
 * @date 2021/8/12 012 - 10:34
 */
@Component
public class CustomFilter implements FilterInvocationSecurityMetadataSource {
      @Autowired
      private IMenuService menuService;

        AntPathMatcher antPathMatcher = new AntPathMatcher();

    @Override
    public Collection<ConfigAttribute> getAttributes(Object object) throws IllegalArgumentException {
        //获取url
        String requestUrl = ((FilterInvocation) object).getRequestUrl();
        System.out.println("requestUrl:"+requestUrl);
        List<Menu> menus = menuService.getMenusFromRole();
        for (Menu menu : menus) {
            //如果匹配
            if (antPathMatcher.match(menu.getUrl(),requestUrl)){
                String[] str = menu.getRoles().stream().map(Role::getCode).toArray(String[]::new);
                return SecurityConfig.createList(str);
            }
        }
        //无匹配给一个登陆角色
        return SecurityConfig.createList("ROLE_LOGIN");
    }

    @Override
    public Collection<ConfigAttribute> getAllConfigAttributes() {
        return null;
    }

    @Override
    public boolean supports(Class<?> aClass) {
        return false;
    }
}
